package other.xsy.paas;

import com.rkhd.platform.sdk.data.model.Contract;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.xsy.paas.utils.HCXObjectService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 功能描述：生成订单编码
 *
 * @author whz
 * @ClassName: OrderTrigger
 * @Description:
 * @date 2023年05月18日
 */
public class OrderTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static Long orderChangeType = 11010003500003L; // 变更单业务类型
    private static Long orderReturnsType = 11010003500002L; // 退货单
    private static Logger logger = LoggerFactory.getLogger();

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Order> orderList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Order order = (Order) xObject;
            orderList.add(order);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        handler(orderList.get(0));
        return new TriggerResponse(true, "", dataResultList);
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        Order order = new Order();
        order.setId(3481122133580463L);
        order = hcxObjectService.get(order);

        OrderTrigger test = new OrderTrigger();
        test.handler(order);
    }

    public void handler(Order order) {
        try {
            String po = order.getPo();
            Long entityType = order.getEntityType();
            if (entityType.equals(orderChangeType) || entityType.equals(orderReturnsType)) {
                logger.info("为退货单或者变更单");
                return;
            }
            logger.info("订单ID：" + order.getId() + " 订单编号：" + po);
            Long contractId = order.getContractId();
            if (contractId == null) {
                logger.info("没有关联合同，无需处理！");
                return;
            }

            // 获取合同编号
            Contract contract = new Contract();
            contract.setId(contractId);
            contract = hcxObjectService.get(contract);
            String contractCode = contract.getContractCode();
            logger.info("合同编号：" + contractCode);

            // 获取订单数据
            List<Order> orderList = queryOtherOrderList(contractId, order.getId());
            logger.info("该合同下其他订单数量：" + orderList.size());
            String newOrderCode = contractCode + getOrderSuffix(orderList);
            logger.info("newOrderCode：" + newOrderCode);
            if (po.equals(newOrderCode)) {
                logger.info("订单编号没有变化，不需要继续执行。");
                return;
            }
            order.setPo(newOrderCode);
            hcxObjectService.update(order);
        } catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
        }
    }

    /**
     * 获取合同序号
     * @param orderList
     * @return
     */
    private String getOrderSuffix(List<Order> orderList) {
        // 如果是合同第一个订单直接返回
        if (orderList == null || orderList.size() <= 0) {
            logger.info("该合同下没有其他订单");
            return "-" + String.format("%02d", 1);
        }

        List<Integer> serialNumberList = new ArrayList<>();
        for (Order order : orderList) {
            String po = order.getPo();

            // 判断是否是新版订单编号
            String[] split = po.split("-");
            if (split.length > 3) {
                // 新版订单编号
                po = split[split.length - 1];
            } else {
                // 旧版本订单编号
                if (!po.contains("(") || !po.contains(")")) {
                    continue;
                }

                po = po.substring(po.indexOf("(") + 1, po.indexOf(")"));
                if (StringUtils.isBlank(po)) {
                    continue;
                }
            }

            boolean isNumeric1 = po.matches("\\d+"); // 使用正则表达式判断是否包含数字
            if (isNumeric1) {
                serialNumberList.add(Integer.valueOf(po));
            }
        }
        System.out.println("serialNumberList = " + serialNumberList);
        if (serialNumberList.size() <= 0) {
            return "-" + String.format("%02d", 1);
        }

        Collections.sort(serialNumberList);
        Integer serialNumber = serialNumberList.get(serialNumberList.size() - 1);
        logger.info("最大流水号：" + serialNumber);
        return "-" + String.format("%02d", serialNumber + 1);
    }

    private List<Order> queryOtherOrderList(Long contractId, Long id) throws Exception {
        String sql =  String.format("select id,po from _order where contractId = %s and id != %s", contractId, id);
        List<Order> orderList = (List<Order>) hcxObjectService.queryAll(sql);
        return orderList;
    }
}
